//
//  MyPurchasingViewController.m
//  XYMaterial
//
//  Created by 肖扬 on 15/12/31.
//  Copyright © 2015年 肖扬. All rights reserved.
//

#import "MyPurchasingViewController.h"
#import "MySupplyOfGoodCess.h"
#import "OrderNullView.h"
@interface MyPurchasingViewController ()<MJRefreshBaseViewDelegate>{
    MJRefreshHeaderView *_header;
    MJRefreshFooterView *_footer;
    NSMutableArray *_fakeData;
    int Page;
    NSString *result;
}

@end

@implementation MyPurchasingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.leftBtn addTarget: self action: @selector(goBackAction) forControlEvents: UIControlEventTouchUpInside];
    self.title = @"我的采购";
    OrderNullView *orderView = [[OrderNullView alloc]initWithFrame:CGRectMake(0, 0, SWIDTH, SHEIGHT-108)];
    [orderView setBackgroundColor:[UIColor clearColor]];
    orderView.tag = 101;
    [orderView setHidden:YES];
    [self.view addSubview:orderView];
    [self setupMainView];
    
    // Do any additional setup after loading the view.
}
-(void)requestPage:(int)page{
    dispatch_async(dispatch_get_main_queue(), ^{
        if (page == 1) {
            [self.mainData removeAllObjects];
        }
        TIME
        HEADDIC(nowTime, MYPURCHAES);
        NSMutableDictionary *body = [NSMutableDictionary dictionary];
        [body setObject:[NSNumber numberWithInt:page] forKey:@"page"];
        requestManage *request = [[requestManage alloc]init];
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setObject:HEAD forKey:@"head"];
        [dic setObject:body forKey:@"body"];
        result = [request post:APPIP postDataDic:dic error:nil];
        NSLog(@"result___%@",result);
        NSMutableDictionary *dict = [result objectFromJSONString];
        NSMutableDictionary *data =[NSMutableDictionary dictionary];
        NSMutableArray *dataArr = [NSMutableArray array];
        if ([dict objectForKey:@"data"]!=[NSNull null]) {
            data = [data objectForKey:@"data"];
        }
        if ([data objectForKey:@"list"]!=[NSNull null]) {
            dataArr = [data objectForKey:@"list"];
        }
//        if ([dataArr count]!=0) {
//            [self.mainTableView setHidden:NO];
//            [self.mainData addObjectsFromArray:dataArr];
//            [self.mainTableView reloadData];
//        }else{
//            NSLog(@"暂无数据");
//            [self.rightBtn setTitle:@"" forState:0];
//            [self.mainTableView setHidden:YES];
//            [self drawNullView];
//        }
        OrderNullView *orderView = (OrderNullView *)[self.view viewWithTag:101];
        if ([dataArr count]!=0) {
            [orderView setHidden:YES];
            [self.mainTableView setHidden:NO];
            [self.mainData addObjectsFromArray:dataArr];
        }else{
            [self.rightBtn setTitle:@"" forState:0];
            [self.mainTableView setHidden:YES];
            [orderView setHidden:NO];
        }
        [self.mainTableView reloadData];
    });
}
- (void)drawNullView{
    UIImageView *imageView = [self createImageViewFrame:CGRectMake((SWIDTH - 47)/2, (SHEIGHT - 63)/2, 47, 63) image:nil imageName:@"暂无采购标识" tag:0];
    [self.view addSubview:imageView];
    
    UILabel *textLab = [self createLabelFrame:CGRectMake(0, (SHEIGHT - 55)/2 + 65, SWIDTH, 14) title:@"这里空空如也～" titleColor:UIColorFromRGB(0xdedede) tag:0];
    textLab.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:textLab];
}
- (void)setupMainView{
    //初始化主页面显示
    UITableView *tempTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 10, SWIDTH, VHEIGHT - 44)];
    [tempTableView setBackgroundColor:UIColorFromRGB(0xf3f2f2)];
    [tempTableView setDelegate:self];
    [tempTableView setDataSource:self];
    UIView *theView = [[UIView alloc] initWithFrame:self.mainTableView.frame];
    [theView setBackgroundColor:[UIColor clearColor]];
    self.mainTableView.separatorStyle = NO;
    self.mainTableView = tempTableView;
    [self.mainTableView setBackgroundView:theView];
    self.mainTableView.tableFooterView=[[UIView alloc]init];
    [self.mainView addSubview:self.mainTableView];
    [self addHeader];
    [self addFooter];
}
- (void)doneWithView:(MJRefreshBaseView *)refreshView
{
    [self requestPage:Page];
    // 刷新表格
    [self.mainTableView reloadData];
    // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    [refreshView endRefreshing];
}
- (void)addFooter
{    __unsafe_unretained MyPurchasingViewController *vc = self;
    MJRefreshFooterView *footer = [MJRefreshFooterView footer];
    footer.scrollView = self.mainTableView;
    footer.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        Page++;
        // 模拟延迟加载数据，因此2秒后才调用）
        // 这里的refreshView其实就是footer
        [vc performSelector:@selector(doneWithView:) withObject:refreshView afterDelay:2.0];
    };
    _footer = footer;
}
- (void)addHeader
{
    __unsafe_unretained MyPurchasingViewController *vc = self;
    MJRefreshHeaderView *header = [MJRefreshHeaderView header];
    header.scrollView = self.mainTableView;
    header.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        Page = 1;
        //        [self dataSource:StateURL];
        // 模拟延迟加载数据，因此2秒后才调用）
        // 这里的refreshView其实就是header
        [vc performSelector:@selector(doneWithView:) withObject:refreshView afterDelay:2.0];
    };
    header.endStateChangeBlock = ^(MJRefreshBaseView *refreshView) {
        // 刷新完毕就会回调这个Block
    };
    header.refreshStateChangeBlock = ^(MJRefreshBaseView *refreshView, MJRefreshState state) {
        // 控件的刷新状态切换了就会调用这个block
        switch (state) {
            case MJRefreshStateNormal:
                break;
            case MJRefreshStatePulling:
                break;
            case MJRefreshStateRefreshing:
                break;
            default:
                break;
        }
    };
    [header beginRefreshing];
    _header = header;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
// 返回每一组有多少行
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.mainData.count;
}

// 返回哪一组的哪一行显示什么内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString* cellId = [NSString stringWithFormat:@"cellid%ld",(long)indexPath.row];
    MySupplyOfGoodCess* cell = (MySupplyOfGoodCess*)[tableView dequeueReusableCellWithIdentifier:cellId];
    if(cell == nil){
        cell = [[MySupplyOfGoodCess alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellId] ;
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    }
    NSMutableDictionary *dic = [self.mainData objectAtIndex:indexPath.row];
    [cell drawCellView:dic];
    return cell;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
